"""
数据库配置和连接管理
"""
from typing import Optional, TYPE_CHECKING
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
from fastapi import FastAPI
from loguru import logger

from .config import settings

if TYPE_CHECKING:
    from app.models.user import User


# Tortoise ORM 配置
TORTOISE_ORM = {
    "connections": {
        "default": settings.database_url,
    },
    "apps": {
        "models": {
            "models": [
                "app.models.user",
                "app.models.customer",
                "app.models.cargo",
                "app.models.equipment",
                "app.models.tracking",
                "app.models.monitoring",
            ],
            "default_connection": "default",
        },
    },
}

# 测试数据库配置
TEST_TORTOISE_ORM = {
    "connections": {
        "default": settings.test_database_url or "sqlite://:memory:",
    },
    "apps": {
        "models": {
            "models": [
                "app.models.user",
                "app.models.customer", 
                "app.models.cargo",
                "app.models.equipment",
                "app.models.tracking",
                "app.models.monitoring",
            ],
            "default_connection": "default",
        },
    },
}


async def init_db() -> None:
    """初始化数据库连接"""
    try:
        await Tortoise.init(config=TORTOISE_ORM)
        logger.info("数据库连接初始化成功")
    except Exception as e:
        logger.error(f"数据库连接初始化失败: {e}")
        raise


async def close_db() -> None:
    """关闭数据库连接"""
    try:
        await Tortoise.close_connections()
        logger.info("数据库连接已关闭")
    except Exception as e:
        logger.error(f"关闭数据库连接失败: {e}")


async def generate_schemas() -> None:
    """生成数据库表结构"""
    try:
        await Tortoise.generate_schemas()
        logger.info("数据库表结构生成成功")
    except Exception as e:
        logger.error(f"生成数据库表结构失败: {e}")
        raise


def register_database(app: FastAPI) -> None:
    """注册数据库到FastAPI应用"""
    register_tortoise(
        app,
        config=TORTOISE_ORM,
        generate_schemas=True,
        add_exception_handlers=True,
    )
    logger.info("数据库已注册到FastAPI应用")


async def create_superuser(
    username: str = "admin",
    email: str = "admin@example.com",
    password: str = "admin123",
    full_name: str = "系统管理员"
) -> Optional["User"]:
    """创建超级用户"""
    from app.models.user import User
    from app.utils.security import get_password_hash
    
    try:
        # 检查用户是否已存在
        existing_user = await User.filter(username=username).first()
        if existing_user:
            logger.info(f"超级用户 {username} 已存在")
            return existing_user
        
        # 创建超级用户
        hashed_password = get_password_hash(password)
        user = await User.create(
            username=username,
            email=email,
            hashed_password=hashed_password,
            full_name=full_name,
            is_superuser=True,
            is_staff=True,
            is_active=True
        )
        
        logger.info(f"超级用户 {username} 创建成功")
        return user
        
    except Exception as e:
        logger.error(f"创建超级用户失败: {e}")
        return None


async def init_default_data() -> None:
    """初始化默认数据"""
    try:
        # 创建默认超级用户
        await create_superuser()
        
        # 创建默认角色和权限
        from app.models.user import Role, Permission
        
        # 创建默认权限
        permissions_data = [
            {"name": "查看用户", "codename": "view_user", "module": "user"},
            {"name": "创建用户", "codename": "create_user", "module": "user"},
            {"name": "编辑用户", "codename": "edit_user", "module": "user"},
            {"name": "删除用户", "codename": "delete_user", "module": "user"},
            {"name": "查看货物", "codename": "view_cargo", "module": "cargo"},
            {"name": "创建货物", "codename": "create_cargo", "module": "cargo"},
            {"name": "编辑货物", "codename": "edit_cargo", "module": "cargo"},
            {"name": "删除货物", "codename": "delete_cargo", "module": "cargo"},
            {"name": "查看客户", "codename": "view_customer", "module": "customer"},
            {"name": "创建客户", "codename": "create_customer", "module": "customer"},
            {"name": "编辑客户", "codename": "edit_customer", "module": "customer"},
            {"name": "删除客户", "codename": "delete_customer", "module": "customer"},
            {"name": "查看装备", "codename": "view_equipment", "module": "equipment"},
            {"name": "创建装备", "codename": "create_equipment", "module": "equipment"},
            {"name": "编辑装备", "codename": "edit_equipment", "module": "equipment"},
            {"name": "删除装备", "codename": "delete_equipment", "module": "equipment"},
            {"name": "查看追踪", "codename": "view_tracking", "module": "tracking"},
            {"name": "管理追踪", "codename": "manage_tracking", "module": "tracking"},
            {"name": "查看监控", "codename": "view_monitoring", "module": "monitoring"},
            {"name": "管理监控", "codename": "manage_monitoring", "module": "monitoring"},
        ]
        
        for perm_data in permissions_data:
            permission, created = await Permission.get_or_create(
                codename=perm_data["codename"],
                defaults=perm_data
            )
            if created:
                logger.info(f"创建权限: {permission.name}")
        
        # 创建默认角色
        admin_role, created = await Role.get_or_create(
            name="管理员",
            defaults={"description": "系统管理员角色，拥有所有权限"}
        )
        if created:
            # 为管理员角色分配所有权限
            all_permissions = await Permission.all()
            await admin_role.permissions.add(*all_permissions)
            logger.info("创建管理员角色并分配所有权限")
        
        # 为超级用户分配管理员角色
        from app.models.user import User
        admin_user = await User.filter(username="admin").first()
        if admin_user:
            await admin_user.roles.add(admin_role)
            logger.info("为超级用户分配管理员角色")
        
        logger.info("默认数据初始化完成")
        
    except Exception as e:
        logger.error(f"初始化默认数据失败: {e}")
        raise
